<template>
  <div class="app-container">
    <el-form :model="form" ref="queryForm" size="small" label-width="120px">
      <el-form-item label="轮播图">
        <el-upload
          :action="uploadImgUrl"
          list-type="picture-card"
          :headers="headers"
          :on-success="handleAvatarSuccess1"
          :file-list="fileList"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove">
          <i class="el-icon-plus"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="首页优惠券">
        <el-upload
          v-loading="loadingup"
          class="avatar-uploader"
          :action="uploadImgUrl"
          :show-file-list="false"
          :headers="headers"
          :limit="1"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload">
          <img v-if="imageUrl" :src="imageUrl" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="优惠券背景图">
        <el-upload
          v-loading="loadingup"
          class="avatar-uploader"
          :action="uploadImgUrl"
          :show-file-list="false"
          :headers="headers"
          :limit="1"
          :on-success="handleAvatarSuccessbg"
          :before-upload="beforeAvatarUpload">
          <img v-if="imageUrlbg" :src="imageUrlbg" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="优惠券说明">
        <editor v-model="form.couponExplain" :min-height="192"/>
      </el-form-item>
      <el-form-item label="政策">
        <el-upload
          v-loading="loadingup"
          class="avatar-uploader"
          :action="uploadImgUrl"
          :show-file-list="false"
          :headers="headers"
          :limit="1"
          :on-success="handleAvatarSuccesszc"
          :before-upload="beforeAvatarUpload">
          <img v-if="imageUrlzc" :src="imageUrlzc" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="small" @click="handleQuery">保存</el-button>
      </el-form-item>
    </el-form>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
import {
  listHomepage,
  getHomepage,
  delHomepage,
  addHomepage,
  updateHomepage,
  getHomeDetail, saveHomeDetail
} from "@/api/business/homepage";
import {getToken} from "@/utils/auth";

export default {
  name: "Homepage",
  data() {
    return {
      uploadImgUrl: process.env.VUE_APP_BASE_API + "/common/upload", // 上传的图片服务器地址
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      fileList: [],
      dialogVisible: false,
      dialogImageUrl: '',
      form: {
        carouselChart: [],
        coupon: '',
        couponExplain: '',
        couponBackground: ''
      },
      loadingup: false,
      imageUrl: '',
      imageUrlbg: '',
      imageUrlzc: "",
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 首页设置表格数据
      homepageList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        configValue: null,
        additionalValue: null,
      },
      // 表单参数
      // 表单校验
      rules: {}
    };
  },
  created() {
    // this.getList();
  },
  mounted() {
    this.getDetail()
  },
  methods: {
    handleQuery() {
      saveHomeDetail(this.form).then(res => {
        this.$message.success('保存成功')
      })
    },
    getDetail() {
      getHomeDetail({id: '1'}).then(res => {
        this.form = res.data
        this.imageUrl = this.form.coupon
        this.imageUrlbg = this.form.couponBackground
        this.imageUrlzc = this.form.policy
        if (this.form.carouselChart) {
          if (this.form.carouselChart.split(',').length > 0) {
            this.form.carouselChart.split(',').forEach(v => {
              this.fileList.push({
                name: v,
                url: v
              })
            })
          }
        }
      })
    },
    beforeAvatarUpload(file) {
      this.loadingup = true
      // const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      // if (!isJPG) {
      //   this.$message.error('上传头像图片只能是 JPG 格式!');
      // }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      // return isJPG && isLt2M;
      return isLt2M;
    },
    handleAvatarSuccess(res, file, fileList) {
      console.log('res', res, fileList)
      this.imageUrl = URL.createObjectURL(file.raw);
      this.form.coupon = res.url
      this.loadingup = false

    },

    handleRemove(file, fileList) {
      const f2=[]

      console.log(file, fileList);
      if (fileList.length > 0) {
        fileList.forEach(v=>{
          if(v.response){
            f2.push(v.response.url)
          }else{
            f2.push(v.url)
          }
        })
        this.form.carouselChart = f2.join(',')

      } else {
        this.form.carouselChart = ''

      }
    },
    handlePictureCardPreview(file) {
      console.log('-----', file)
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleAvatarSuccess1(res, file, fileList) {
      console.log(fileList)
      const f1=[]
      fileList.forEach(v=>{
        if(v.response){
          f1.push(v.response.url)
        }else{
          f1.push(v.url)
        }
      })
      this.form.carouselChart = f1.join(',')

      // fileList.forEach(v=>{
      //   console.log('res1', v)
      //
      //   if(!v.response){
      //     v.response.url = v.url
      //   }
      // })
      //
      // this.form.carouselChart = fileList.map(v => v.response.url).join(',')


    },
    handleAvatarSuccessbg(res, file, fileList) {
      console.log('res', res, fileList)
      this.imageUrlbg = URL.createObjectURL(file.raw);
      this.form.couponBackground = res.url
      this.loadingup = false


    },
    handleAvatarSuccesszc(res, file, fileList) {
      console.log('res', res, fileList)
      this.imageUrlzc = URL.createObjectURL(file.raw);
      this.form.policy = res.url
      this.loadingup = false


    },
    /** 查询首页设置列表 */
    getList() {
      this.loading = true;
      listHomepage(this.queryParams).then(response => {
        this.homepageList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        configValue: null,
        additionalValue: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加首页设置";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getHomepage(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改首页设置";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateHomepage(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addHomepage(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除首页设置编号为"' + ids + '"的数据项？').then(function () {
        return delHomepage(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('mobile/homepage/export', {
        ...this.queryParams
      }, `homepage_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style scoped>
.avatar-uploader /deep/ .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader /deep/ .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
